package org.tang.springcloudvv.mybatis;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.CompilationUnit;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.internal.DefaultCommentGenerator;
import org.mybatis.generator.internal.util.StringUtility;
import org.springframework.util.StringUtils;

import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 自定义Swagger注解生成器
 * @author shengshenglalala
 */
public class CommentGenerator extends DefaultCommentGenerator {
    /**
     * 是否需要生成字段备注信息
     */
    private boolean addRemarkComments = false;
    private static final String EXAMPLE_SUFFIX="Example";
    private static final String PROVIDER_SUFFIX="Provider";
    private static final String API_MODEL_PROPERTY_FULL_CLASS_NAME="io.swagger.annotations.ApiModelProperty";
    private static final String API_MODEL_FULL_CLASS_NAME="io.swagger.annotations.ApiModel";
    private static final String JSON_INCLUDE_FULL_CLASS_NAME ="com.fasterxml.jackson.annotation.JsonInclude";

    /**
     * 设置用户配置的参数
     */
    @Override
    public void addConfigurationProperties(Properties properties) {
        super.addConfigurationProperties(properties);
        this.addRemarkComments = StringUtility.isTrue(properties.getProperty("addRemarkComments"));
    }

    /**
     * 给字段添加注释
     */
    @Override
    public void addFieldComment(Field field, IntrospectedTable introspectedTable,
                                IntrospectedColumn introspectedColumn) {
        String remarks = introspectedColumn.getRemarks();
        String jdbcTypeName = introspectedColumn.getJdbcTypeName();
        //根据参数和备注信息判断是否添加备注信息
        if(addRemarkComments&& StringUtility.stringHasValue(remarks)){
//            addFieldJavaDoc(field, remarks);
            //数据库中特殊字符需要转义
            if(remarks.contains("\"")){
                remarks = remarks.replace("\"","'");
            }
            if(remarks.contains("\r")){
                remarks = remarks.replace("\r"," ");
            }
            if(remarks.contains("\n")){
                remarks = remarks.replace("\n"," ");
            }
            String example = getExampleNameByJdbcType(jdbcTypeName,remarks);
            String javaDocLine = "@ApiModelProperty(value = \""+remarks+"\")";
            if(!StringUtils.isEmpty(example)){
                javaDocLine = "@ApiModelProperty(value = "+"\""+remarks+"\" , "+"example = "+"\""+example+"\""+")";
            }
            //给model的字段添加swagger注解
            field.addJavaDocLine(javaDocLine);
        }
    }

    /**
     * 通过jdbcType获取example信息
     * @param jdbcTypeName jdbcTypeName
     * @param remarks 备注信息
     * @return example信息
     */
    private String getExampleNameByJdbcType(String jdbcTypeName, String remarks) {
        String example = "";
        switch (jdbcTypeName.toUpperCase()){
            case "BIT":
            case "TINYINT":
            case "SMALLINT":
            case "INTEGER":
            case "BIGINT":
            case "FLOAT":
            case "REAL":
            case "DOUBLE":
            case "NUMERIC":
            case "DECIMAL": example = "0";break;
            case "CHAR":
            case "VARCHAR":
            case "LONGVARCHAR":example = remarks;break;
            case "DATE":example = "2021-01-01";break;
            case "TIME":example = "00:00:00";break;
            case "TIMESTAMP":example = "2021-01-01 00:00:00";break;
            case "BINARY":
            case "VARBINARY":
            case "LONGVARBINARY":example = "[]";break;
            default:break;
        }
        return example;
    }

    /**
     * 添加类注释
     * @param topLevelClass 类相关信息
     * @param introspectedTable 数据库表相关信息
     */
    @Override
    public void addModelClassComment(TopLevelClass topLevelClass, IntrospectedTable introspectedTable) {
        String tableName = introspectedTable.getAliasedFullyQualifiedTableNameAtRuntime();
        tableName = underlineToHump(tableName);
        topLevelClass.addJavaDocLine("@ApiModel(value = \""+ tableName +"\")");
        topLevelClass.addJavaDocLine("@JsonInclude(JsonInclude.Include.NON_NULL)");
        super.addModelClassComment(topLevelClass, introspectedTable);
    }

    /**
     * 下划线转驼峰
     * @param str   目标字符串
     * @return java.lang.String
     */
    public static String underlineToHump(String str) {
        String regex = "_(.)";
        Matcher matcher = Pattern.compile(regex).matcher(str);
        while (matcher.find()) {
            String target = matcher.group(1);
            str = str.replaceAll("_"+target, target.toUpperCase());
        }
        return str;
    }

    /**
     * 给model的字段添加注释
     */
    private void addFieldJavaDoc(Field field, String remarks) {
        //文档注释开始
        field.addJavaDocLine("/**");
        //获取数据库字段的备注信息
        String[] remarkLines = remarks.split(System.getProperty("line.separator"));
        for(String remarkLine:remarkLines){
            field.addJavaDocLine(" * "+remarkLine);
        }
        addJavadocTag(field, false);
        field.addJavaDocLine(" */");
    }

    @Override
    public void addJavaFileComment(CompilationUnit compilationUnit) {
        super.addJavaFileComment(compilationUnit);
        //只在model中添加swagger注解类的导入
        if(!compilationUnit.isJavaInterface()
                &&!compilationUnit.getType().getFullyQualifiedName().contains(EXAMPLE_SUFFIX)
                &&!compilationUnit.getType().getFullyQualifiedName().contains(PROVIDER_SUFFIX)){
            compilationUnit.addImportedType(new FullyQualifiedJavaType(API_MODEL_PROPERTY_FULL_CLASS_NAME));
            compilationUnit.addImportedType(new FullyQualifiedJavaType(API_MODEL_FULL_CLASS_NAME));
            compilationUnit.addImportedType(new FullyQualifiedJavaType(JSON_INCLUDE_FULL_CLASS_NAME));
        }
    }
}